package com.edol.painting.main;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.edol.painting.PainterConfig;
import com.edol.painting.R;
import com.edol.painting.data.PaintingDatabase;
import com.edol.painting.data.PaintingListLoader;
import com.edol.painting.utils.Constant;
import com.edol.painting.utils.DefaultRationale;
import com.edol.painting.utils.PermissionSetting;
import com.meituan.android.walle.WalleChannelReader;
import com.umeng.analytics.MobclickAgent;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2017/7/3.
 */

public class PaintMainActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<List<PaintingDatabase.PaintingEntry>>,
        View.OnClickListener, AdapterView.OnItemClickListener {
    private Unbinder mBinder;
    private PaintController mPaintController;
    private Handler mHandler;

    private View mActionBar;
    private ImageView mMenuSwitcher;
    private DrawerLayout mDrawerLayout;
    private ListView mLeftDrawer;
    private ImageView mCreatePaintBtn;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paint_main);

        mHandler = new Handler();
        mBinder = ButterKnife.bind(this);
        mPaintController = PaintController.getInstances();

        mActionBar = findViewById(R.id.action_bar);
        mMenuSwitcher = (ImageView) findViewById(R.id.menu_switcher);
        mCreatePaintBtn = (ImageView) findViewById(R.id.create_btn);
        mCreatePaintBtn.setOnClickListener(this);
        mMenuSwitcher.setOnClickListener(this);
        //load left drawerr
        loadLeftDrawer();

        mPaintController.enterPaintListPage(this);
        getSupportLoaderManager().initLoader(0, null, this);

        //init
        Constant.initCommonValue(this);

        //umeng
        String channelId = WalleChannelReader.getChannel(getApplicationContext());
        MobclickAgent.UMAnalyticsConfig config = new MobclickAgent.UMAnalyticsConfig(this, PainterConfig.UMENG_APPKEY, channelId, MobclickAgent.EScenarioType.E_UM_NORMAL);
        MobclickAgent.startWithConfigure(config);
        //MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);

        gradePermission();
    }

    @Override
    protected void onResume() {
        super.onResume();

        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();

        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBinder != null) {
            mBinder.unbind();
        }

        if (mPaintController != null) {
            mPaintController.destroy();
        }
    }

    private void loadLeftDrawer() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.draw_layout);
        mLeftDrawer = (ListView) findViewById(R.id.left_drawer);
        mLeftDrawer.setOnItemClickListener(this);
        String[] leftData = getResources().getStringArray(R.array.left_menu);
        LeftDrawerAdapter adapter = new LeftDrawerAdapter(this, leftData);
        mLeftDrawer.setAdapter(adapter);

        mDrawerLayout.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                mMenuSwitcher.setImageResource(R.drawable.ic_main_menu_back);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                mMenuSwitcher.setImageResource(R.drawable.ic_main_menu_open);
            }

        });

    }

    //======================load data===================================
    @Override
    public Loader<List<PaintingDatabase.PaintingEntry>> onCreateLoader(int id, Bundle args) {
        return new PaintingListLoader(this);
    }

    @Override
    public void onLoadFinished(Loader<List<PaintingDatabase.PaintingEntry>> loader, final List<PaintingDatabase.PaintingEntry> data) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mPaintController.notifyPaintListChange(PaintMainActivity.this, data);
            }
        });
    }

    @Override
    public void onLoaderReset(Loader<List<PaintingDatabase.PaintingEntry>> loader) {
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!handleOnBackPressed()) {
                return false;
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (handleOnBackPressed()) {
            super.onBackPressed();
        }
    }

    private boolean handleOnBackPressed() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        List<Fragment> fragmentList = fragmentManager.getFragments();
        Fragment topFragment = null;
        if (fragmentList != null && fragmentList.size() > 0) {
            int size = fragmentList.size();
            for (int i = size - 1; i >= 0; i--) {
                topFragment = fragmentList.get(i);
                if (topFragment != null) {
                    break;
                }
            }
        }
        if (topFragment instanceof PaintEditFragment) {
            if (((PaintEditFragment) topFragment).onBackPressed()) {
                return false;
            }
        }

        return true;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.create_btn:
                PaintController.getInstances().enterBlankPaint(this);
                break;
            case R.id.menu_switcher:
                if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
                    mDrawerLayout.closeDrawer(Gravity.LEFT);
                } else {
                    mDrawerLayout.openDrawer(Gravity.LEFT);
                }
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        mDrawerLayout.closeDrawer(Gravity.LEFT, false);
        switch (position) {
            case 0:
                startActivity(new Intent(PaintMainActivity.this, ShareQrcodeActivity.class));
                break;
            case 1:
                startActivity(new Intent(PaintMainActivity.this, AboutUsActivity.class));
                break;
            case 2:
                //startActivity(new Intent(PaintMainActivity.this, FeedbackActivity.class));
                joinQQ(PainterConfig.QQ_GROUP_ID);
                break;
        }
    }

    public void hideActionBar() {
        if (mActionBar != null) {
            mActionBar.setVisibility(View.GONE);
        }
    }

    public void showActionBar() {
        if (mActionBar != null) {
            mActionBar.setVisibility(View.VISIBLE);
        }
    }

    public void unLockDrawer() {
        if (mDrawerLayout != null) {
            mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        }
    }

    public void lockDrawer() {
        if (mDrawerLayout != null) {
            mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        }
    }

    private void gradePermission() {
        String[] permissions = new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CAMERA
        };

        final DefaultRationale rationale = new DefaultRationale();
        final PermissionSetting setting = new PermissionSetting(this);
        if (Build.VERSION.SDK_INT >= 23) {
            AndPermission
                    .with(this)
                    .permission(permissions)
                    .rationale(rationale)
                    .onGranted(new Action() {
                        @Override
                        public void onAction(List<String> permissions) {

                        }
                    })
                    .onDenied(new Action() {
                        @Override
                        public void onAction(List<String> permissions) {
                            if (AndPermission.hasAlwaysDeniedPermission(PaintMainActivity.this, permissions)) {
                                setting.showSetting(permissions);
                            }
                        }
                    }).start();
        }
    }

    private void joinQQ(String qq) {
        try {
            String url = "mqqapi://card/show_pslcard?src_type=internal&version=1&uin=" + qq + "&card_type=group&source=qrcode";
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, "没有安装QQ!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void overridePendingTransition(int enterAnim, int exitAnim) {
        super.overridePendingTransition(0, 0);
    }
}